package com.syqc.utils

import android.annotation.SuppressLint
import android.os.Build
import android.text.Html
import android.text.InputFilter
import android.text.Spanned
import android.view.MotionEvent
import android.widget.EditText
import java.util.regex.Matcher
import java.util.regex.Pattern


/**
 *@Author pc_hfjs
 *@Date 2022/4/18 14:32
 *@Desc
 */
object InputUtil {

    //数字  汉字 字母
    private const val speChat = "[^a-zA-Z0-9-\\u4E00-\\u9FA5]"

    //emoji表情符
    private const val emoji =
        "(?:[\uD83C\uDF00-\uD83D\uDDFF]|[\uD83E\uDD00-\uD83E\uDDFF]|[\uD83D\uDE00-\uD83D\uDE4F]|[\uD83D\uDE80-\uD83D\uDEFF]|" +
                "[\u2600-\u26FF]\uFE0F?|[\u2700-\u27BF]\uFE0F?|\u24C2\uFE0F?|[\uD83C\uDDE6-\uD83C\uDDFF]{1,2}|" +
                "[\uD83C\uDD70\uD83C\uDD71\uD83C\uDD7E\uD83C\uDD7F\uD83C\uDD8E\uD83C\uDD91-\uD83C\uDD9A]\uFE0F?|" +
                "[\u0023\u002A\u0030-\u0039]\uFE0F?\u20E3|[\u2194-\u2199\u21A9-\u21AA]\uFE0F?|" +
                "[\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55]\uFE0F?|[\u2934\u2935]\uFE0F?|[\u3030\u303D]\uFE0F?|[\u3297\u3299]\uFE0F?|" +
                "[\uD83C\uDE01\uD83C\uDE02\uD83C\uDE1A\uD83C\uDE2F\uD83C\uDE32-\uD83C\uDE3A\uD83C\uDE50\uD83C\uDE51]\uFE0F?|[\u203C\u2049]\uFE0F?|" +
                "[\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE]\uFE0F?|[\u00A9\u00AE]\uFE0F?|[\u2122\u2139]\uFE0F?|\uD83C\uDC04\uFE0F?|\uD83C\uDCCF\uFE0F?|" +
                "[\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA]\uFE0F?)"


    /**
     * 禁止EditText输入空格
     */
    fun setInhibitInputSpaChat(editText: EditText, length: Int = 20) {
        val filterSpace =
            InputFilter { source, start, end, dest, dstart, dend -> if (source == " ") "" else null }
        val filterSpeChat =
            InputFilter { charSequence, i, i1, spanned, i2, i3 ->
                val pattern: Pattern = Pattern.compile(speChat)
                val matcher: Matcher = pattern.matcher(charSequence.toString())
                if (matcher.find()) "" else null
            }
        editText.filters = arrayOf(filterSpace, filterSpeChat, InputFilter.LengthFilter(length))
    }

    /**
     * 禁止EditText输入空格
     */
    fun setInputSpaChat(editText: EditText) {

        val filterSpeChat =
            InputFilter { charSequence, i, i1, spanned, i2, i3 ->
                val pattern: Pattern = Pattern.compile("^[a-zA-Z0-9_\\u4E00-\\u9FA5]|[@()-]+$")
                val matcher: Matcher = pattern.matcher(charSequence.toString())
                if (matcher.find()) null else ""
            }
        editText.filters = arrayOf(filterSpeChat)
    }

    /**
     * 禁止EditText输入空格
     */
    fun setInputChat(editText: EditText, length: Int = 20, isSpace: Boolean = false) {
        val filterSpeChat =
            InputFilter { charSequence, i, i1, spanned, i2, i3 ->
                val pattern: Pattern = Pattern.compile("^[a-zA-Z0-9_\\u4E00-\\u9FA5]|[@()-]+$")
                val matcher: Matcher = pattern.matcher(charSequence.toString())
                if (matcher.find()) null else ""
            }
        if (isSpace) {
            editText.filters = arrayOf(filterSpeChat, InputFilter.LengthFilter(length))
        } else {
            val filterSpace =
                InputFilter { source, _, _, _, _, _ -> if (source == " ") "" else null }
            editText.filters = arrayOf(filterSpace, filterSpeChat, InputFilter.LengthFilter(length))
        }
    }

    /**
     * 禁止EditText输入空格
     */
    fun setInputChat(editText: EditText, length: Int = 20) {
        val filterSpace =
            InputFilter { source, _, _, _, _, _ -> if (source == " ") "" else null }
        val filterSpeChat =
            InputFilter { charSequence, i, i1, spanned, i2, i3 ->
                val speChat = "^[0-9A-Za-z_]\$"
                val pattern: Pattern = Pattern.compile(speChat)
                val matcher: Matcher = pattern.matcher(charSequence.toString())
                if (matcher.find()) null else ""
            }
        editText.filters = arrayOf(filterSpace, filterSpeChat, InputFilter.LengthFilter(length))
    }
    fun noInputSpace(editText: EditText) {
        val filterSpace = InputFilter { source, start, end, dest, dstart, dend ->
            // 使用正则表达式去除所有空白字符
            val result = source.toString().replace("\\s".toRegex(), "")
            // 如果有空白字符被移除，则返回处理后的结果
            if (result.length != end - start) result else null
        }

        editText.filters = arrayOf(filterSpace)
    }
//    /**
//     * 禁止EditText输入空格
//     */
//    fun noInputSpace(editText: EditText) {
//        val filterSpace =
//            InputFilter { source, _, _, _, _, _ -> if (source == " ") "" else null }
//
//        editText.filters = arrayOf(filterSpace)
//    }

    /**
     * 判断是否含有特殊字符
     */
    fun isHadSpecial(input: String): Boolean {
        val pattern: Pattern = Pattern.compile(speChat)
        val matcher: Matcher = pattern.matcher(input)
        return matcher.matches()
    }

    /**
     * 禁止EditText输入表情符和空格
     * 输入最大长度默认 20
     */
    fun setInputRemark(editText: EditText, length: Int = 20, isSpace: Boolean = false) {
        val filterSpeChat =
            InputFilter { charSequence, _, _, _, _, _ ->
                // 过滤emoji
                val pattern =
                    Pattern.compile(emoji)
                val matcher = pattern.matcher(charSequence.toString())
                if (matcher.find()) "" else null
            }
        if (isSpace) {
            val filterSpace =
                InputFilter { source, _, _, _, _, _ -> if (source == " ") "" else null }
            editText.filters = arrayOf(filterSpace, filterSpeChat, InputFilter.LengthFilter(length))
        } else {
            editText.filters = arrayOf(filterSpeChat, InputFilter.LengthFilter(length))
        }
    }

    /**
     * 禁止EditText输入表情符
     */
    fun setInhibitInputSpaChatRemark(editText: EditText, length: Int = 100) {
        val filterSpeChat =
            InputFilter { charSequence, i, i1, spanned, i2, i3 ->
                // 过滤emoji
                val pattern =
                    Pattern.compile(emoji)
                val matcher = pattern.matcher(charSequence.toString())
                if (matcher.find()) "" else null
            }
        editText.filters = arrayOf(filterSpeChat, InputFilter.LengthFilter(length))
    }

    /**
     * EditText滑动冲突，NestedScrollView嵌套EditText
     */
    @SuppressLint("ClickableViewAccessibility")
    fun editTextNested(edittext: EditText) {
        edittext.setOnTouchListener { view, motionEvent ->
            when (motionEvent.action) {
                MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
                    //通知父控件不要干扰
                    view.parent.requestDisallowInterceptTouchEvent(true)
                }
                MotionEvent.ACTION_UP -> {
                    view.parent.requestDisallowInterceptTouchEvent(false)
                }
            }
            false
        }
    }

    /**
     * Created by chenglin on 2017-3-21.
     * 自定义的InputFilter ，用来限制英文中文输入字符限制。两个汉字代表一个英文。
     */
    class EnglishCharFilter(len: Int) : InputFilter {
        var maxLen = 0

        /**
         * 输入英文的最大长度 。比如你想要限制40个汉字，80个英文字符，传入的值就是80
         * 使用方式：mEdit.setFilters(new InputFilter[]{filter});
         */
        init {
            maxLen = len
        }

        override fun filter(
            src: CharSequence,
            start: Int,
            end: Int,
            dest: Spanned,
            dstart: Int,
            dend: Int
        ): CharSequence? {
            var dindex = 0
            var count = 0
            while (count <= maxLen && dindex < dest.length) {
                val c = dest[dindex++]
                count = if (c.code and 0xffff <= 0xff) {
                    count + 1
                } else {
                    count + 2
                }
            }
            if (count > maxLen) {
                return dest.subSequence(0, dindex - 1)
            }
            var sindex = 0
            while (count <= maxLen && sindex < src.length) {
                val c = src[sindex++]
                count = if (c.code and 0xffff <= 0xff) {
                    count + 1
                } else {
                    count + 2
                }
            }
            if (count > maxLen) {
                sindex--
                return src.subSequence(0, sindex)
            }
            return null
        }

        companion object {
            fun calculateLength(c: CharSequence, english: Boolean): Int {
                var len = 0.0
                for (i in 0 until c.length) {
                    val cc = c[i]
                    if (cc.code and 0xffff <= 0xff) {
                        len += 0.5
                    } else {
                        len++
                    }
                }
                if (english) {
                    len = len * 2
                }
                return Math.round(len).toInt()
            }
        }
    }
}

/**
 * 禁止EditText输入空格
 */
fun EditText.setInputChat(length: Int = 20, isSpace: Boolean = false) {
    val filterSpeChat =
        InputFilter { charSequence, i, i1, spanned, i2, i3 ->
            val pattern: Pattern = Pattern.compile("^[a-zA-Z0-9_\\u4E00-\\u9FA5]|[@()-]+$")
            val matcher: Matcher = pattern.matcher(charSequence.toString())
            if (matcher.find()) null else ""
        }
    if (isSpace) {
        filters = arrayOf(filterSpeChat, InputUtil.EnglishCharFilter(length))
    } else {
        val filterSpace =
            InputFilter { source, _, _, _, _, _ -> if (source == " ") "" else null }
        filters = arrayOf(filterSpace, filterSpeChat, InputUtil.EnglishCharFilter(length))
    }

}

fun String.isNumChar(): Boolean {
    return this.matches("^[a-z0-9A-Z]+$".toRegex())
}

fun setDescStar(desc: String): Spanned {
    val htmlStr = "<font color='#111111'>$desc</font><font color='#FF0000'>*</font>"
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Html.fromHtml(htmlStr, Html.FROM_HTML_MODE_LEGACY)
    } else {
        Html.fromHtml(htmlStr)
    }
}